package com.learn.english.service.impl;

import com.learn.english.constants.CacheConstants;
import com.learn.english.enums.TimeEnum;
import com.learn.english.mapper.TopBannerMapper;
import com.learn.english.model.entity.TopBanner;
import com.learn.english.model.ro.BannerRo;
import com.learn.english.service.ITopBannerService;
import com.learn.english.service.RedisService;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author TISNIW
 * @version 1.0
 * @desc
 */

@Service
@Slf4j
public class TopBannerServiceImpl implements ITopBannerService {
    @Autowired
    private TopBannerMapper topBannerMapper;
    @Autowired
    private RedisService redisService;

    @Override
    public List<BannerRo> getTopBanner(Integer pageId) {
        // 构建缓存键
        String cacheKey = CacheConstants.BANNER_CACHE_KEY + pageId;
        log.info("cacheKey: {}", cacheKey);
        // 尝试从缓存中获取数据，使用类型安全的方式
        List<?> rawBanners = redisService.getCacheObject(cacheKey, List.class);
        List<BannerRo> banners = null;
        if (rawBanners != null && !rawBanners.isEmpty()) {
            // 安全地转换为List<BannerRo>
            banners = new ArrayList<>();
            for (Object obj : rawBanners) {
                if (obj instanceof BannerRo) {
                    banners.add((BannerRo) obj);
                }
            }
            if (!banners.isEmpty()) {
                return banners;
            }
        }
        log.info("banners from cache: {}", banners);
        // 缓存未命中，查询数据库
        banners = topBannerMapper.getTopBanner(pageId);
        log.info("banners: {}", banners);
        if (banners != null && !banners.isEmpty()) {
            // 设置缓存，过期时间为5分钟
            redisService.setCacheObject(cacheKey, banners, TimeEnum.FIVE_MINUTE);
        }

        return banners;
    }

    @Override
    
    public int addTopBanner(TopBanner topBanner) {
        int rows = topBannerMapper.addTopBanner(topBanner);
        if (rows > 0) {
            // 插入成功后清空对应缓存
            String cacheKey = CacheConstants.BANNER_CACHE_KEY + topBanner.getType();
            redisService.deleteObject(cacheKey);
        }
        return rows;
    }
}